<?php


namespace App\Http\Controllers\Mini;

use App\Http\Controllers\Controller;
use App\Models\BalanceLogs;
use App\Models\Configs;
use App\Models\IntegralLogs;
use App\Models\Mails;
use App\Models\OrderPays;

use App\Models\Orders;
use App\Models\ProfitLogs;
use App\Models\SignUps;
use App\Models\Users;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    public $wxConfig;

    public function __construct()
    {

        $wx_config = config("wechat.payment.default");
        $this->wxConfig = $wx_config;
    }

    //获取微信公众号用户授权
    public function wxAuth(){
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
    }

    //需要调用微信支付时调用该方法
    public function wxPayment($pay_sn='',$product_id='',$price=0,$title='',$detail='',$notify_url = '',$type='JSAPI',$open_id=''){

        $attributes = [
            'trade_type'       => $type,
            'body'             => $title,
            'detail'           => $detail,
            'out_trade_no'     => $pay_sn,
            'product_id'        => $product_id,
            'total_fee'        => 1,
            'notify_url'       => $notify_url,
            'openid'          => $open_id
        ];
        $app = Factory::payment($this->wxConfig);

        $result = $app->order->unify($attributes);
      //  var_dump($result);
        if( $result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            if($type=='NATIVE'){
                return [
                    'code' => 1,
                    'msg' => "生成支付二维码成功",
                    'data' => $result['code_url'],
                ];
            } elseif($type=='JSAPI'){
                $result = $app->jssdk->bridgeConfig($result['prepay_id'], false); // 返回数组//第二次签名
                return [
                    'code' => 1,
                    'msg' => "生成支付订单成功",
                    'data' => $result
                ];
            }
        } else{
            Log::error('微信支付签名失败:',$result);
            return ["code"=>0, "msg"=>"支付订单生成失败"];
        }
    }

    /**
     * 商品支付回调
     */
    public function goodsNotifyUrl()
    {
        $app = Factory::payment($this->wxConfig);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            //处理订单
            Log::info('微信支付回调:',$message);
            if ($message["result_code"] == "SUCCESS" && $message["return_code"]) {
                try{
                    //支付单信息
                    $pay_info = OrderPays::where("pay_sn", $message["out_trade_no"])->first();
                    $order_info = Orders::where("pay_sn", $message["out_trade_no"])->first();
                    if($order_info["pay_status"]==1){

                        //修改订单信息
                        $order_info->pay_status = 2;
                        $order_info->pay_time = date('Y-m-d H:i:s');
                        $order_info->order_state = 3;
                        $order_info->save();

                        $pay_info->pay_status = 1;
                        $pay_info->save();

                        //hr赠送积分
                        $integral = Configs::getConfig('integral');
                        Users::where('id',$order_info['user_id'])->increment('integral',$integral['hr_goods']);
                        //发送站内信-积分增加通知
                        $template = [
                            'title' => '购买商品获得积分',
                            'content' => '您购买的商品获得"' . $integral['hr_goods'] .'"积分，支付单号为：'. $order_info['pay_sn'],
                            'user_id' => $order_info['user_id'],
                            'status' => 1,
                            'type' => 1,
                        ];
                        Mails::create($template);
                        //积分日志记录
                        $integral = [
                            'user_id' => $order_info['user_id'],
                            'user_name' => $order_info['user_name'],
                            'integral' => '+'.$integral['hr_goods'],
                            'desc' => '购买商品获得积分',
                            'type' => 1,
                        ];
                        IntegralLogs::create($integral);
                        //收益日志记录
                        $profit = [
                            'user_id' => $order_info['user_id'],
                            'user_name' => $order_info['user_name'],
                            'profit' => '+'.$order_info['pay_price'],
                            'desc' => 'HR购买商品获得收益',
                            'type' => 1,
                        ];
                        ProfitLogs::create($profit);
                    }
                    return 'SUCCESS';// 返回处理完成
                }catch (\Exception $e) {
                    Log::info($e->getMessage());
                }
            }
        });

        return $response;
    }

    /**
     * 活动支付回调
     */
    public function actNotifyUrl()
    {
        $app = Factory::payment($this->wxConfig);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            //处理订单
            Log::info('微信活动支付回调:',$message);
            if ($message["result_code"] == "SUCCESS" && $message["return_code"]) {
                try{
                    //支付单信息
                    $pay_info = SignUps::where("pay_sn", $message["out_trade_no"])->first();
                    if($pay_info["pay_state"]==1){
                        //修改订单信息
                        $pay_info->pay_state = 2;
                        $pay_info->pay_way = 2;
                        $pay_info->pay_at = date('Y-m-d H:i:s');
                        $pay_info->save();
                    }
                    return 'SUCCESS';// 返回处理完成
                }catch (\Exception $e) {

                }
            }
        });
        return $response;
    }

    /**
     * 供应商余额充值支付回调
     */
    public function balanceNotifyUrl()
    {
        $app = Factory::payment($this->wxConfig);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            //处理订单
            if ($message["result_code"] == "SUCCESS" && $message["return_code"]) {
                try{
                    //支付单信息
                    $pay_info = BalanceLogs::where("pay_sn", $message["out_trade_no"])->first();
                    if($pay_info["pay_state"]==1){
                        //修改订单信息
                        $pay_info->pay_state = 2;
                        $pay_info->pay_at = date('Y-m-d H:i:s');
                        $pay_info->save();
                    }
                    Users::where('id',$pay_info['user_id'])->increment('balance',$pay_info['money']);
                    //发送站内信-积分增加通知
                    $template = [
                        'title' => '余额充值',
                        'content' => '恭喜您，充值成功。充值金额为：' + $pay_info['money'],
                        'user_id' => $pay_info['user_id'],
                        'status' => 1,
                        'type' => 1,
                    ];
                    Mails::create($template);

                    return true;// 返回处理完成
                }catch (\Exception $e) {

                }
            }
        });
        return $response;
    }
}